package cn.smile.utils;

import cn.smile.commons.constant.NumberConstant;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;

import java.util.regex.Pattern;

/**
 * @author smile-jt
 */
@Slf4j
public class IpUtils {

    private final static String UNKNOWN = "unknown";
    private final static String SYMBOL = ",";
    private final static String REGULAR = "^([1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}$";

    /**
     * get remote ip address
     */
    public static String getRemoteIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Real-IP");
        if (ObjectUtils.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ObjectUtils.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ObjectUtils.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (ObjectUtils.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("http_client_ip");
        }
        if (ObjectUtils.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ObjectUtils.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("x-forwarded-for");
        }
        // 如果是多级代理,那么取第一个ip为客户ip
        if (!ObjectUtils.isEmpty(ip) && ip.contains(SYMBOL)) {
            ip = ip.substring(ip.lastIndexOf(SYMBOL) + NumberConstant.ONE).trim();
        }
        return ip;
    }

    /**
     * 检查是否符合IP格式
     *
     * @param ip ip地址
     * @return true-符合, false-不符合
     */
    public static boolean checkIp(String ip) {
        return Pattern.matches(REGULAR, ip);
    }
}
